import java.io.IOException;
import pnt.client.PNTTCPClient;

//
//  PNTLibrary.java
//  PNTLibrary
//
//  Created by Andrew on 4/12/07.
//  Copyright (c) 2007 __MyCompanyName__. All rights reserved.
//

import java.net.*;
import java.util.logging.*;
import pnt.server.*;

public class PNTLibrary {
    
    private static Logger logger = Logger.getLogger("pnt.client");
    
    public static final int DEFAULT_PORT = 1234;
    
    
    public static void main (String args[]) {
        setupLogging();
        parseInput(args); 
    }

    public static boolean client (String address, String svrport, String lclport) {
        int sport = Integer.parseInt(svrport);
        int lport = Integer.parseInt(lclport);
        return client(address, sport, lport);
    }

    public static boolean client (String svraddress, int svrport, int lclport) {

        logger.info("Initialising client, connecting to " + svraddress + ":" + svrport);
        try {
            
        PNTTCPClient client = new PNTTCPClient(Inet4Address.getByName(svraddress), svrport, lclport);
        client.open();
        client.discoverNAT();
        client.close();
        return true;
        
        } catch (IOException ex) {
            
            System.err.println(ex.getMessage() + ". Unable to establish connection.\n");
            return false;
        
        } catch (Exception e) {
        
            e.printStackTrace();
            System.err.println();
            return false;
        }
    }

    public static boolean server () {
        logger.info("Initialising server");
        Server.getServer().run();
        return true;
    }
    
    private static class LogFormatter extends java.util.logging.Formatter{
        @Override
        public String format(LogRecord record) {
            String s = "";
            // time header
            s += "-- " + record.getLevel().getName() + " --\n";
            s += "   " + record.getMessage() + "\n";
            if (record.getParameters() != null){
                for (Object o : record.getParameters()){
                    String[] lines = o.toString().split("\n");
                    for (String line : lines)
                        s += "      " + line + "\n";

                    s += "   --\n";
                }
            }
            return s;
        }
    }
    
    public static class LogHandler extends java.util.logging.Handler{

        @Override
        public void publish(LogRecord record) {
            System.out.println(this.getFormatter().format(record));
        }

        @Override
        public void flush() {
            
        }

        @Override
        public void close() throws SecurityException {
            
        }
        
    }
    
    public static void setupLogging(){

        Handler ch = new LogHandler();
        ch.setFormatter(new LogFormatter());
        Logger.getLogger("").removeHandler(Logger.getLogger("").getHandlers()[0]);
        Logger.getLogger("").addHandler(ch);
        Logger.getLogger("").setLevel(Level.FINE);

        
    }

    public static void parseInput(String args[]){
        // Input format is "PNT client <supernodeIP:Port> <localport>| server <listeningport>"
        if ( args.length == 1 ) {
             if (args[0].compareToIgnoreCase("server") == 0){
                    server();
            } else {
                    System.out.println("PNT client <supernodeIP:Port> <localport>| server");
            }
        } else if (args.length == 3) {
             if(args[0].compareToIgnoreCase("client") == 0 && 
                    client(args[1], "" + DEFAULT_PORT, args[2])){
            } else {
                    System.out.println("PNT client <supernodeIP:Port> <localport>| server ");
            }
        } else if (args.length == 4) {
            if(args[0].compareToIgnoreCase("client") == 0 && 
                    client(args[1], args[2], args[3])){
            } else {
                    System.out.println("PNT client <supernodeIP:Port> <localport>| server ");
            }
        } else {
        
                System.out.println("PNT client <supernodeIP:Port> <localport>| server ");
        }
    }
}
